package com.seari.tunnel.security;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.jframe.util.DigestsUtil;
import com.jframe.util.EncodeUtils;
import com.seari.tunnel.entity.User;
import com.seari.tunnel.service.IUserService;

/**
 * Title:ShiroRealm
 * Description:
 * @authot JFM
 * @date 2016年1月4日 下午4:00:45
 */
public class ShiroRealm extends AuthorizingRealm{
	
	private static final Logger log = LoggerFactory.getLogger(ShiroRealm.class);
	
	private static final int INTERATIONS = 1024;
	
	@Autowired
	protected IUserService userService;

	
	
	
	/**
	 * 认证回调函数, 登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
		User user = userService.getUserByName(token.getUsername());
		if(user != null){
			if(user.getStatus()!=1){
				throw new DisabledAccountException();
			}
			byte[] salt = EncodeUtils.hexDecode(user.getSalt());
			
			ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUsername(), user);
			
			// 这里可以缓存认证
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(shiroUser,
					user.getPassword(), getName());
			info.setCredentialsSalt(ByteSource.Util.bytes(salt));
			
			return info;
		}else{
			return null;
		}
		
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser username = (ShiroUser) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(userService.findRoleByUserName(username.getLoginName()));
		return info;
	}
	
	
	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	/**
	 * 
	 * 验证密码
	 * @param plainPassword 明文密码
	 * @param password 密文密码
	 * @param salt 盐值
	 * @return
	 */
	public static boolean validatePassword(String plainPassword, String password, String salt) {
		byte[] hashPassword = DigestsUtil.sha1(plainPassword.getBytes(), EncodeUtils.hexDecode(salt), INTERATIONS);
		String oldPassword = EncodeUtils.hexEncode((hashPassword));
		return password.equals(oldPassword);
	}


}
